package com.ubb.damate.filters;

import java.io.IOException;

import javax.faces.FactoryFinder;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.ubb.damate.beans.UserSessionBean;

public class AuthorizationFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,	FilterChain chain) throws IOException, ServletException {
		FacesContext ctx = getFacesContext(request, response);
		if (ctx != null && ctx.getApplication().evaluateExpressionGet(ctx, "#{userSession}", UserSessionBean.class) != null) {
			UserSessionBean bean = (UserSessionBean) ctx.getApplication().evaluateExpressionGet(ctx, "#{userSession}", UserSessionBean.class);
			if (bean.isAuthorized()) {
				chain.doFilter(request, response);
			} else {
				String relativePath = ((HttpServletRequest)request).getServletPath();
				if (!relativePath.equals("/login.jsf") && !relativePath.equals("/registration.jsf")) {
					((HttpServletRequest)request).getServletContext().getRequestDispatcher("/login.jsf").forward(request, response);
				} else {
					chain.doFilter(request, response);
				}
			}
	    } else {
	    	chain.doFilter(request, response);
	    }
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	
	}
	
	public FacesContext getFacesContext(final ServletRequest request, final ServletResponse response)
    {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (facesContext != null)
        {
            return facesContext;
        } 
        FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
        LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
        Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
        ServletContext servletContext = ((HttpServletRequest) request).getSession().getServletContext();
        facesContext = contextFactory.getFacesContext(servletContext, request, response, lifecycle); 
        return facesContext;
    }

}
